define([],
function(_client){

	var _showLoading = function(speed){
		$("loading").show(speed || 50);
	}
	
	var _hideLoading = function(speed){
		$("loading").hide(speed || 50);
	}
	
	window.oldalert = window.alert;
	
	window.goApp = function(url, selector){
		$(selector).html("");
		return $.pjax({
			url: url,
			container: selector
		});
	}
	
	window.loadApp = function(url, selector){
        // console.warn("loadApp in '" + selector + "' - " + url)
		$(selector).html("");
		return appendApp(url, selector);
	}
	
	window.appendApp = function(url, selector, async){
		return $.ajax({
			url: url,
			async : async
		}).done(function(data){
			// console.warn("appendApp in '" + selector + "' - " + url)
			$(selector).append(data);
            initWrapper();
		});
	}

    /**
	 * 获取url中的参数name
	 * @param {Object} name
	 */
	window.getQueryString = function(name) {
		var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
		var r = window.location.search.substr(1).match(reg);
		if (r != null) {
			return unescape(r[2]);
		}
		return null;
	}

	function setDomHeight(selector, percent){
//		debugger;
		$(selector).each(function(i, item){
			var width = $(item).width();
			var height = width / percent;
			$(item).css("height", height + "px");
		});
	}
	
	function goReferrer(){
		if(window.location.href != document.referrer)
			window.location.href = document.referrer
	}

	function initWrapper(){
		var height = window.innerHeight;
//		oldalert(height);
		var $wrapper = $("wrapper").css("height", height + "px");
		$wrapper.show();
		var $app = $("app").css("height", "auto");
		if($app.height() <=  $wrapper.height()){
			$app.css("height", $wrapper.height() + 1 + "px");
		}
		_hideLoading(200);
	}
	
	$(window).resize(function(){
		setTimeout(initWrapper,100);
	});

    function sendInjectPost(tabId, url, cookie, data){
        return injectProxy(tabId, "sendPost", {
            url : url,
            cookie : cookie,
            data : data
        })
    }

    function sendInjectGet(tabId, url, cookie){
        return injectProxy(tabId, "sendGet", {
            url : url,
            cookie : cookie,
        })
    }

    /**
     *   注入代理，向content-script 发送消息，tabId     </br>
     *   协议如下：
     *
     *   >>> 以json形式发送：
     *      {
     *          "func":"functionName", // 方法名
     *          "data":{...}           // json形式
     *      }
     *
     *   <<< 以json形式返回：
     *      {
     *          "code":0,     // 返回结果，code = 0 则调用成功，否则返回错误码
     *          "message": ""， // code != 0 时返回错误原因，调用成功不返回
     *          "data":{...}    // 调用成功的返回结果
     *      }
     *
     *   @param tabId chrome的tabId
     *   @param funcName content-script中定义的方法名
     *   @param data 消息体，作为funcName对应方法的参数
     *   @param successFunc 调用成功的回调方法 - 也可不传使用promise的链式调用
     *   @param errorFunc 调用失败的回调方法 - 也可不传使用promise的链式调用
     *
     *   @return 返回一个promise对象，可使用.then .done .fail进行链式调用
     */
	var injectProxy = function(tabId, funcName, data, successFunc, errorFunc){
        var respObj = $.Deferred();
        chrome.tabs.sendMessage(tabId, {
            func: funcName,
            data: data
        }, function(_resp){
            console.info("receive resp : " + JSON.stringify(_resp));
            var success = _resp && _resp.code === 0
            if(success){
                var result = _resp.data;
                if("string" === typeof result){
                    if(result.indexOf("{") === 0 && result.lastIndexOf("}") === result.length - 1){
                        result = JSON.parse(result);
                    }
                }
                if("function" === typeof successFunc){
                    successFunc(result);
                }
                respObj.resolve(result);
            } else {
                var e = {
                    errcode : _resp ? _resp.code : -1,
                    message : _resp ? _resp.message : "内部错误"
                }
                if("function" === typeof errorFunc){
                    errorFunc(e)
                }
                respObj.reject(e);
            }
        });
        return respObj.promise();
    }


	var ajaxGet = function(url, headers) {
		return $.ajax({
			type: "get",
			url: url,
			async: true,
			headers: headers,
		});
	}

	var ajaxPost = function(url, headers, data) {
		return $.ajax({
			type: "post",
			url: url,
			async: true,
			headers: headers,
			data: data
		});
	}
	
	return {
		client : _client,
		initWrapper :initWrapper,
		setDomHeight : setDomHeight,
		showLoading : _showLoading,
		hideLoading : _hideLoading,
		goReferrer : goReferrer,
        sendPost : sendInjectPost,
        sendGet : sendInjectGet,
		ajaxPost : ajaxPost,
		ajaxGet : ajaxGet
	};
	
});